package com.neusoft.service.impl;

import com.neusoft.exception.FailToInitCredit;
import com.neusoft.exception.FailtocreateWallet;
import com.neusoft.feign.CreditFeignClient;
import com.neusoft.feign.WalletFeignClient;
import com.neusoft.mapper.UserMapper;
import com.neusoft.po.User;
import com.neusoft.service.UserService;
import com.neusoft.util.CommonUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CreditFeignClient creditFeignClient;
    @Autowired
    private WalletFeignClient walletfeignclient;

    @Override
    public User getUserByIdByPass(User user) {
        user.setPassword(CommonUtil.getSHA256Hash(user.getPassword()));
        User rUser=null;
        if (userMapper.getUserByIdByPass(user) != null) {
            rUser=userMapper.getUserByIdByPass(user);
            rUser.setPassword("");
        }
        return rUser;
    }

    @Override
    public int getUserById(String userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    @Transactional(rollbackFor = {FailToInitCredit.class, FailtocreateWallet.class})
    public int saveUser(User user) throws FailToInitCredit, FailtocreateWallet {
        user.setPassword(CommonUtil.getSHA256Hash(user.getPassword()));

        int res=userMapper.saveUser(user);

        if(creditFeignClient.initCredit(user.getUserId()).getCode()!=200){
            throw new FailToInitCredit("初始化积分失败！");
        }
        if(walletfeignclient.createWallet(user.getUserId()).getCode()!=200){
            throw new FailtocreateWallet("初始化钱包失败");
        }

        return res;
    }

    @Override
    public int isRider(User user) {
        return userMapper.isRider(user);
    }

    @Override
    public int updateAsRider(User user) {
        return userMapper.updateAsRider(user);
    }

//    @Override
//    public Double getBalanceByUserId(String userId){
//        return userMapper.getBalanceByUserId(userId);
//    }
//
//    @Override
//    public int updateBalance(User user){
//        return userMapper.updateBalance(user);
//    }
}
